#!/usr/bin/env python

def single_space(s):
    "Given a string, converts all multiple spaces present in it into a single space"
    while -1 != s.find('  '):
        s = s.replace('  ', ' ')
    
    return s

def remove_space(s):
    "Given a string, removes all spaces from it"
    while -1 != s.find(' '):
        s = s.replace(' ', '')
    
    return s

def seq_to_str(seq, sep=',', surrounding_str=''):
    "Given a sequence, converts it into string with each item separated by sep"
    s = ''
    for i in seq:
        s = s + surrounding_str + str(i) + surrounding_str + sep
    
    if len(s)>0:
        s = s[:len(s)-len(sep)]
    
    return s

def split_seq(seq, num_of_pieces):
    newseq = []
    splitsize = 1.0/num_of_pieces*len(seq)
    for i in range(num_of_pieces):
        newseq.append(seq[int(round(i*splitsize)):int(round((i+1)*splitsize))])
    
    return newseq

def time_period_to_seconds(time_period):
    """Given a time period, returns the total number of seconds present in the time period
    for example,
    time_period='5 minutes' will return 300
    
    supported time periods are: seconds, minutes, hours and days
    examples:
        5 mintues
        10 hours 30 minutes
        5 days 7 hours 12 minutes 30 seconds
    """
    
    import re
    
    def single_period_word_to_secs(period_word):
        "Returns a single time period word like '3 mintues' converted to seconds, useful for supporting multiple words"
        parts = single_space(period_word).split(' ')
        value = int(parts[0])
        unit = parts[1].lower()
        
        unit_multiplier = {'seconds': 1,
                           'minutes': 60,
                           'hours': 3600,
                           'days': 86400
                           }
        
        return value*unit_multiplier[unit]
    
    r = re.compile("\d+\s+\w+", re.U)
    pwords = r.findall(time_period)
    secs = 0
    for pword in pwords:
        secs += single_period_word_to_secs(pword)
    
    return secs

    
